package com.qf.aop2204.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.lang.reflect.Method;

@Aspect
@Component
public class CalulateTimeAspect {
    @Around("@annotation(com.qf.aop2204.aop.CalculateTime)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("~~~~~~~~~~~~~~~~~");
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        System.out.println("~~~~~~~~~~~~~~~~~");
        long end = System.currentTimeMillis();
        String login = "time used->"+(end-start);
        System.out.println(login);
        //通过spring框架传入的pjp对象，可以获取到目标方法对象
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        //获取到目标方法对应的反射Method对象
        Method method = signature.getMethod();
        //获取目标方法上面的注解 @Calculate
        CalculateTime annotation = method.getAnnotation(CalculateTime.class);
        String logfilepath = annotation.logfilepath();
        int time = annotation.time();
        if (logfilepath != null && !logfilepath.equals((""))) {
            //添加方法执行时长信息到文本文件中
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logfilepath, true));
            if ((end-start)>time) {
                bufferedWriter.write(login);
                bufferedWriter.newLine();
                bufferedWriter.close();
            }
        }
        return result;
    }
}
